package com.xiaoying.server.publish.task;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xiaoying.server.publish.comomon.upyun.UpYunUtil;
import com.xiaoying.server.publish.entity.FileInfo;
import com.xiaoying.server.publish.entity.UploadResult;
import com.xiaoying.server.publish.upload.UploadFile;
import com.xiaoying.server.publish.utils.DateUtil;

public class UploadDealTask implements Runnable {
	private static Log log = LogFactory.getFactory().getInstance(UploadDealTask.class);
	
	private BlockingQueue<FileInfo> fileUploadQueue;
	private BlockingQueue<UploadResult> uploadResultQueue;
	private FileInfo fileInfo;
	private AtomicInteger idleThread;
	
	public UploadDealTask(BlockingQueue<FileInfo> fileUploadQueue,
			BlockingQueue<UploadResult> uploadResultQueue,
			FileInfo fileInfo,AtomicInteger idleThread){
		this.fileInfo = fileInfo;
		this.fileUploadQueue = fileUploadQueue;
		this.uploadResultQueue = uploadResultQueue;
		this.idleThread = idleThread;
	}
	
	
	@Override
	public void run() {
		// 设置线程工作状态
		this.setThreadStatusBusy();
		UploadResult uploadResult = UploadFile.upload(fileUploadQueue,uploadResultQueue,fileInfo);
		try {
			if(uploadResult.getResultType()==UploadResult.TYPE_FAIL){				
				int maxCount = this.getMaxUploadCount(fileInfo.getFileType());
				if(fileInfo.getUploadCount()<=maxCount){
					// 上传失败,次数小于最大上传次数,放入队列末尾重新上传
					fileInfo.setUploadCount(fileInfo.getUploadCount()+1);
					uploadResult.setResultType(UploadResult.TYPE_SUCCESS);
					this.fileUploadQueue.put(fileInfo);
					log.debug("文件["+fileInfo.getFileName()+"]上传失败,重新上传,已上传 ["+fileInfo.getUploadCount()+"]次");
				}else{
					// 上传次数太多了,设置错误Type=count_exceed,加入result队列
					log.error("文件 ["+fileInfo.getFileName()+"]上传失败,上传次数太多");
					uploadResult.setResultType(UploadResult.TYPE_FAIL_COUNT_EXCEED);
					this.uploadResultQueue.add(uploadResult);
				}
			}else{
				// 上传成功
				log.info("文件["+fileInfo.getFileName()+"]上传成功");
				this.uploadResultQueue.add(uploadResult);
			}
		} catch (InterruptedException e) {
			log.error("重传文件["+uploadResult.getRemotePath()+"]放入队列失败, 原因:"+e);
		}
		// 释放线程
//		System.out.println("已经释放了线程!! 空闲线程数量="+this.releaseThread());
		uploadResult = null;
		this.releaseThread();
	}
	
	/**
	 * 获取文件上传最大次数
	 * @param fileType
	 * @return
	 */
	private int getMaxUploadCount(int fileType){
		return fileType==UpYunUtil.FILETYPE_VIDEO?
				UpYunUtil.MAX_VIDEO_UPLOAD_COUNT:UpYunUtil.MAX_IMAGE_UPLOAD_COUNT;
	}
	
	/**
	 * 设置线程状态繁忙
	 * @return
	 */
	private int setThreadStatusBusy(){
		return this.idleThread.decrementAndGet();
	}
	
	/**
	 * 线程结束，释放线程
	 * @author ZJD
	 * @return
	 */
	private int releaseThread(){		
		return this.idleThread.incrementAndGet();
	}

}
